package org.bbb.library1.editors;

import org.bbb.library1.model.Book;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.editor.FormEditor;

//import com.finalist.rcp.core.Book;

/**
 * @author Rob Schellhorn
 */
public class BookEditor extends FormEditor {

   public static final String EDITOR_ID = "org.bbb.library1.editors.book";

   /*
    * @see org.eclipse.ui.forms.editor.FormEditor#addPages()
    */
   @Override
   protected void addPages() {
      try {
         addPage(new OverviewFormPage(this));
         //addPage(new AuthorsFormPage(this));
      } catch (PartInitException e) {
         e.printStackTrace();
      }
   }

   /*
    * @see org.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.IProgressMonitor)
    */
   @Override
   public void doSave(IProgressMonitor monitor) {
      try {
         monitor.beginTask("Saving the book", 3);

         // commit the form contents to the book
         commitPages(true);
         monitor.worked(1);

         // notify of the state change
         editorDirtyStateChanged();
         monitor.worked(1);

         // notify the book's observers
         Book book = getEditorInput().getBook();
         if (book.hasChanged()) {
            book.notifyObservers();
         }
         monitor.worked(1);
      } finally {
         monitor.done();
      }
   }

   /*
    * @see org.eclipse.ui.part.EditorPart#doSaveAs()
    */
   @Override
   public void doSaveAs() {/* Not allowed */}

   /*
    * @see org.eclipse.ui.part.EditorPart#getEditorInput()
    */
   @Override
   public BookEditorInput getEditorInput() {
      return (BookEditorInput) super.getEditorInput();
   }

   /*
    * @see org.eclipse.ui.forms.editor.FormEditor#init(org.eclipse.ui.IEditorSite,
    *      org.eclipse.ui.IEditorInput)
    */
   @Override
   public void init(IEditorSite site, IEditorInput input) throws PartInitException {
      if (!(input instanceof BookEditorInput)) {
         throw new PartInitException("The input is not an instance of " + BookEditor.class);
      }

      super.init(site, input);
      setPartName(BookEditorInput.class.cast(input).getName());
   }

   /*
    * @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed()
    */
   @Override
   public boolean isSaveAsAllowed() {
      return false;
   }

}
